﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WPFDemo.View
{
    /// <summary>
    /// FileTreeView.xaml 的交互逻辑
    /// </summary>
    public partial class FileTreeView : Window
    {
        public FileTreeView()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            foreach (var drive in Directory.GetLogicalDrives())
            {
                var item = new TreeViewItem()
                {
                    Header = drive,
                    Tag = drive
                };
                

                item.Items.Add(null);

                item.Expanded += Folder_Expand;

                FolderView.Items.Add(item); 
            }
        }

        private void Folder_Expand(object sender, RoutedEventArgs e)
        {
            var item = (TreeViewItem)sender;
            if (item.Items.Count != 1 || item.Items[0] != null)
            {
                return;
            }
            item.Items.Clear();

            var fullPath = (string)item.Tag;

            var directories = new List<string>();
            try
            {
                var dirs = Directory.GetDirectories(fullPath);
                if (dirs.Length > 0)
                    directories.AddRange(dirs);
            }
            catch (Exception)
            {
                throw;
            }

            directories.ForEach(d =>
            {
                var subItem = new TreeViewItem()
                {
                    Header = GetFileFolderName(d),
                    Tag = d
                };

                subItem.Items.Add(null);
                subItem.Expanded += Folder_Expand;

                item.Items.Add(subItem);
            });

        }

        public static string GetFileFolderName(string path)
        {
            if (string.IsNullOrEmpty(path))
                return string.Empty;
            var normalizedPath =path.Replace("/", "\\");
            var lastIndex = normalizedPath.LastIndexOf('\\');
            if (lastIndex <= 0)
                return path;
            return path.Substring(lastIndex+1);

        }
    }
}
